package com.zhoufy.tomcat.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-03-30.
 *
 * @author zhoufy
 */
public class StaticResourcesUtil {

    /**
     *    获取静态资源文件的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String absoluteResourcePath = StaticResourcesUtil.class.getResource("/").getPath();
        return absoluteResourcePath.replace("\\\\", "/") + path;
    }


    /**
     *    读取静态资源文件输入流 通过输出流输出
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        // 输出http 请求头
        outputStream.write(HttpProtocolUtil.getHttpHeader200(count).getBytes());

        /*
            输出内容
         */
        // 已经读取的内容
        long written = 0;
        // 计划每次缓冲的长度
        int byteSize = 1024;

        byte[] buffer = new byte[byteSize];
        while (written < count) {
            //  剩余未读大小不足1024  那按真是长度读取
            if( written + byteSize > count) {
                byteSize = (int) (count - written);
                buffer = new byte[byteSize];
            }
            inputStream.read(buffer);
            outputStream.write(buffer);
            outputStream.flush();
            written += byteSize;
        }

    }
}
